//app.js
import config from 'utils/config.js'
import {Request} from 'utils/request.js'

let callBack = null;

App({
  onLaunch: function () {
    this.updateFun();
    let userInfo = wx.getStorageSync('userInfo');
    let authorization = wx.getStorageSync('authorization');
    if(userInfo) {
      this.globalData.userInfo = userInfo;
    }
    if(authorization) {
      this.globalData.authorization = authorization;
    }


    this.onLogin();
    

  },


  //登录，仅仅获取openid或unionid
  onLogin: function() {
      var that = this;
      wx.login({
          success: res => {
              let param = {
                url: 'user/login',
                method: 'POST',
                data: {
                  code: res.code,
                }
              }
              Request(param).then(function(res){
                  //处理登录
                  let authorization = res.data.token;
                  wx.setStorageSync('authorization', authorization);
                  wx.setStorageSync('userInfo', res.data.user);
                  that.globalData.userInfo = res.data.user;
                  that.globalData.authorization = authorization;

                  that.globalData.shareText = res.data.config.text;
                  that.globalData.shareCover = res.data.config.cover;
                  that.globalData.wxad = res.data.wxad;
                  if(that.callBack){
                    that.callBack();
                  }
              });
          },
      })
  },

  
  



checkLogin: function() {
  let that = this;
  if(that.globalData.userInfo.is_wechat_info == 0) {
    var pages = getCurrentPages();
    var prevPage = pages[pages.length - 1];
    prevPage.setData({
      showLogin: true,
    })
    return false;
  }else {
    return true;
  }
},



  getUserInfo: function(e, successCallBack = function(res){}) {
      var that = this;
      var login = new Promise((resolve, reject) => {
        wx.login({
          success: res => {
            // 这里也可以选择性返回需要的字段
            resolve(res)
          }
        })
      })
      var userinfo = new Promise((resolve, reject) => {
        wx.getUserProfile({
          desc: '用于完善会员资料',
          success: res => {
            // 这里也可以选择性返回需要的字段
            resolve(res)
          }
        })
      })
      // 同时执行p1和p2，并在它们都完成后执行then
      Promise.all([login, userinfo]).then((results) => {
        // results是一个长度为2的数组，放置着p1、p2的resolve
        this.handleUserInfo({
            // 这里也可以选择性返回需要的字段
            ...results[0],
            ...results[1]
        }, successCallBack)
      })

  },

  handleUserInfo (data, successCallBack) {
  	const { code, encryptedData, userInfo, iv } = data;
    let that = this;
    let reqData = {
      url: 'user/login',
      method: 'POST',
      data: {
        code: code,
        iv: iv,
        encryptedData: encryptedData
      }
    }
    Request(reqData).then(function(res){
        //处理登录
        let authorization = res.data.token;
        wx.setStorageSync('authorization', authorization);
        wx.setStorageSync('userInfo', res.data.user);
        that.globalData.userInfo = res.data.user;
        that.globalData.authorization = authorization;
        var pages = getCurrentPages();
        var prevPage = pages[pages.length - 1];
        console.log(pages, prevPage, 1232);
        prevPage.setData({
          showLogin: false,
        });
        successCallBack(res);
    });

  },


  /**
   * 用户点击右上角分享
   */
  shareAppMessage: function (url, title, img) {
      var url = url ? url : "/pages/index/index";
      var title = title ? title : this.globalData.shareText;
      var img = img ? img : this.globalData.shareCover;
      return {
          title: title,
          path: url,
          imageUrl: img
      }
  },
  





    /**判断小程序是否要更新 */
    updateFun: function () {
      const updateManager = wx.getUpdateManager()
      updateManager.onCheckForUpdate(function (res) {
          // 请求完新版本信息的回调
          // console.log(res.hasUpdate)
      })
      updateManager.onUpdateReady(function () {
          wx.showModal({
              title: '更新提示',
              content: '新版本已经准备好，是否重启应用？',
              success: function (res) {
                  if (res.confirm) {
                      // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                      updateManager.applyUpdate()
                  }
              }
          })
      })
      updateManager.onUpdateFailed(function () {
          // 新版本下载失败
          wx.showModal({
              title: '更新提示',
              content: '新版本下载失败，请自行重启应用！',
              success: function (res) {
                  if (res.confirm) {
                  }
              }
          })
      })
    },

  globalData: {
    userInfo: null,
    authorization: null,
    wxad: {},
    shareText: '',
    shareCover: '',
  }
})